package com.tz.online.user.action;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.tz.online.book.service.IBookService;
import com.tz.online.common.PageBean;
import com.tz.online.entity.Book;
import com.tz.online.entity.Gender;
import com.tz.online.entity.User;
import com.tz.online.exception.LoginException;
import com.tz.online.user.service.IUserService;
import com.tz.online.util.BeanFactory;

/**
 * Servlet implementation class BookAction
 */
@WebServlet("/user/*")
public class UserAction extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	/** 业务接口 */
	private IUserService userService;

	/** 请求资源URL常量 */
	private static final String _TO_REGISTER = "/toregister";  //进入注册页面
	private static final String _REGISTER = "/register"; //注册
	private static final String _TO_LOGIN = "/tologin"; //进入登录界面
	private static final String _LOGIN = "/login"; //登录
	private static final String _LOGOUT = "/logout"; //注销
	private static final String _TO_MODIFY = "/tomodify"; //进入修改个人信息页面
	private static final String _MODIFY = "/modify"; //修改个人信息
	private static final String _VALIDATE_NAME = "/validateName"; //验证用户名是否可用
	
	//地址相关
	private static final String _ADDRESS_ADD = "/addr/add"; //添加用户收货地址
	private static final String _ADDRESS_UPDATE = "addr/update"; //更新用户收货地址
	private static final String _ADDRESS_DELETE = "/addr/delete"; //删除用户收货地址
	private static final String _ADDRESS_LIST = "/addr/list"; //列出用户的所有可用收货地址
	
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UserAction() {
		super();
		//初始化业务接口
		this.userService = (IUserService) BeanFactory.getBean("userService");
	}

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1.获取 servletpath
		String servletPath = request.getServletPath();
		if (servletPath.equals("/user")) {
			// 2.拿到 pathinfo
			String pathInfo = request.getPathInfo();
			// 3.根据这个pathinfo 来做出不同的处理
			switch (pathInfo) {
			case _TO_REGISTER:
				//转发
				forward(request, response, true, "/WEB-INF/jsp/user/register.jsp");
				break;
			case _REGISTER:
				// 获取请求参数
				String username = request.getParameter("username");
				String password = request.getParameter("password");
				String realname = request.getParameter("realname");
				String gender = request.getParameter("gender");
				String email = request.getParameter("email");
				String tel = request.getParameter("tel");
				String corparate = request.getParameter("corparate");
				
				//创建 User 对象
				User user = new User();
				//绑定属性值
				user.setUserName(username);
				user.setPassword(password);
				user.setGender(gender.equals("0") ? Gender.MALE : Gender.FEMALE);
				user.setEmail(email);
				user.setTel(tel);
				user.setCompany(corparate);
				user.setRealName(realname);
				//
				System.out.println("注册的用户信息："+user);
				//保存
				userService.register(user);
				//重定向到登录页面
				forward(request, response, false, "/user/tologin");
				break;
			case _TO_LOGIN:
				//直接转发
				forward(request, response, true, "/WEB-INF/jsp/user/login.jsp");
				break;
			case _LOGIN:
				//获取 请求参数
				username = request.getParameter("username");
				password = request.getParameter("password");
				String terms = request.getParameter("terms");
				//调用业务方法
				try {
					User u = userService.login(username, password);
					//如果没有出现异常，则说明登录成功，所用户绑定到 session 范围
					HttpSession session = request.getSession();
					session.setAttribute("user", u);
					Cookie nameCookie = new Cookie("username", username);
					Cookie pwdCookie = new Cookie("pwd", password);
					//则进一步判断是否需要保存帐号和密码
					if(terms != null && terms.equals("1")) {
						//说明需要保存帐户和密码到 cookie中
						nameCookie.setMaxAge(2 * 7 * 24 * 60 * 60);
						nameCookie.setPath(getServletContext().getContextPath());
						
						pwdCookie.setMaxAge(2 * 7 * 24 * 60 * 60);
						pwdCookie.setPath(getServletContext().getContextPath());
						//把此cookie写到浏览器端
						response.addCookie(nameCookie);
						response.addCookie(pwdCookie);
						//
						System.out.println(">>>> 把用户名和密码的cookie写入到浏览器端成功");
					} else {
						//说明用户不保存了
						nameCookie.setMaxAge(0);
						pwdCookie.setMaxAge(0);
						//
						System.out.println(">>>> 在浏览器端删除cookie成功...");
					}
					//重定向
					forward(request, response, false, "/book/index");
					//
				} catch (LoginException e) {
					System.out.println(">>> "+e.getMessage());
					//把错误消息绑定到请求范围
					request.setAttribute("login_error", e.getMessage());
					//转发到登录页面
					forward(request, response, true, "/WEB-INF/jsp/user/login.jsp");
					//
				}
				break;
			case _LOGOUT:
				//
				request.getSession().removeAttribute("user");
				request.getSession().invalidate();
				//重定向
				forward(request, response, false, "/book/index");
				break;
			case _TO_MODIFY:
				
				break;
			case _MODIFY:
				
				break;
				
			//AJAX相关
			case _VALIDATE_NAME:
				//注册时验证用户名
				
				break;
			case _ADDRESS_ADD:
				//添加用户的收货地址
				
				break;
			case _ADDRESS_UPDATE:
				//更新用户的收货地址
				
				break;
			case _ADDRESS_DELETE:
				//删除用户的收货地址
				
				break;
			case _ADDRESS_LIST:
				//列出用户的所有收货地址
				
				break;
			default:
				// 非法的请求
				response.sendError(HttpServletResponse.SC_BAD_REQUEST, "你所请求的路径是非法的");
				break;
			}

		} else {
			// 不合法法的 servletpath
			// ...
		}
	}
	
	/***************
	 * 转发或重定向请求
	 * 
	 * @param request
	 * @param response
	 * @param b
	 *            为真，则转换请求，为false,则重定向请求
	 * @param target
	 *            目标资源
	 * @throws IOException
	 * @throws ServletException
	 */
	private void forward(HttpServletRequest request, HttpServletResponse response, boolean b, String target)
			throws ServletException, IOException {
		if (b) {
			RequestDispatcher rd = getServletContext().getRequestDispatcher(target);
			rd.forward(request, response);
			return;
		} else {
			String contextPath = getServletContext().getContextPath();
			response.sendRedirect(contextPath+target);
			return ;
		}
	}

}
